<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of uploadActionclass
 *
 * @author Eshton
 */
class uploadAction extends sfAction {
    public function execute ($request) {
        $i18n = sfContext::getInstance()->getI18N();
        $form = new ReplayForm();
        $this->form = $form;
        if ($request->isMethod('post')) {
            $form->bind($request->getParameter('replay'), $request->getFiles('replay'));
            if ($form->isValid()) {

                /*
                 * Prepare data
                 */
                $newReplay = $form->getObject();
                $newReplay->setUserId(1);
                $newReplay->setGameTypeId(1);
                $newReplay->setCreatedAt(time());
                $newReplay->setDescription($form->getValue('description'));
                $newReplay->setCategoryId($form->getValue('category_id'));

                /*
                 * Save file
                 */
                $file = $form->getValue('replay_file');
                $path = pathinfo($file->getOriginalName());
                $extension = $path['extension'];
                if (strtolower($extension) != 'sc2replay') {
                    $this->getUser()->setFlash('error_message', $i18n->__('Ehh, ez tényleg sc2 replay???'));
                    return sfView::SUCCESS;
                }
                try {
                    $filename = $newReplay->generatePreparedFileName();
                }
                catch(Exception $e) {
                    $this->getUser()->setFlash('error_message', $e->getMessage());
                    return sfView::SUCCESS;
                }
                
                $fileSavePath = sfConfig::get('sf_upload_dir').'/replay/'.$filename;
                $file->save($fileSavePath);

                $newReplay->setFileName($filename);

                $result = $newReplay->parseData();

                if (!$result) {
                    unlink($fileSavePath);
                    $this->getUser()->setFlash('error_message', $i18n->__('Nem tudtam parse-olni a fájlt!'));
                    return sfView::SUCCESS;
                }

                $newReplay->save();
                
                $this->getUser()->setFlash('success_message', $i18n->__('Sikeres feltöltés!'));
                $this->redirect('replay/browse');
            }
        }
    }
}
?>
